package com.zlt.miaosha.service;

import com.zlt.miaosha.dao.MiaoshaUserDao;
import com.zlt.miaosha.domain.MiaoshaUser;
import com.zlt.miaosha.exception.GlobalException;
import com.zlt.miaosha.redis.MiaoshaUserKey;
import com.zlt.miaosha.redis.RedisService;
import com.zlt.miaosha.result.CodeMsg;
import com.zlt.miaosha.util.MD5Util;
import com.zlt.miaosha.util.UUIDUtil;
import com.zlt.miaosha.vo.LoginVo;
import jdk.nashorn.internal.parser.Token;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhoulitong
 * @date 2018/6/13
 * @description
 */
@Service
public class MiaoshaUserService {

    public static final String COOKIE_NAME_TOKEN = "token";
    @Resource
    MiaoshaUserDao miaoshaUserDao;
    @Resource
    RedisService redisService;

    /**
     * 根据id获取秒杀user
     * @param id
     * @return
     */
    public MiaoshaUser getById(long id){

        //取缓存
        MiaoshaUser user = redisService.get(MiaoshaUserKey.getById, "" + id, MiaoshaUser.class);
        if (user != null) {
            return user;
        }
        //取数据库
        user = miaoshaUserDao.getById(id);
        if (user != null) {
            redisService.set(MiaoshaUserKey.getById, "" + id, user);
        }
        return user;
    }

    /**
     * 更新密码，并更新redis中的用户信息
     * @param token
     * @param id
     * @param formPass
     * @return
     */
    public boolean updatePassword(String token,long id, String formPass) {
        //取user
        MiaoshaUser user = getById(id);
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //注意：这里为了提高更新效率，不建议直接更新传进来的实体对象，建议更新指定字段
        MiaoshaUser toBeUpdate = new MiaoshaUser();
        toBeUpdate.setId(id);
        toBeUpdate.setPassword(MD5Util.formPassToDBPass(formPass,user.getSalt()));
        miaoshaUserDao.update(toBeUpdate);
        //处理缓存
        redisService.delete(MiaoshaUserKey.getById, "" + id);
        redisService.set(MiaoshaUserKey.token, token, user);
        return true;
    }

    /**
     * 登录是否成功
     * @param loginVo
     * @param response
     * @return
     */
    public /*boolean*/ String login(LoginVo loginVo,HttpServletResponse response) {
        if (StringUtils.isEmpty(loginVo)) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVo.getMobile();
        String formPass = loginVo.getPassword();
        //判断手机号是否存在
        MiaoshaUser user = getById(Long.parseLong(mobile));
        if (StringUtils.isEmpty(user)) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //验证密码
        String dbPass = user.getPassword();
        String saltDB = user.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
        if (!calcPass.equals(dbPass)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        String token = UUIDUtil.uuid();
        //生成cookie
        addCookie(response,token,user);
        return /*true*/token;
    }

    /**
     * 延长cookie的有效期
     * @param response
     * @param token
     * @return
     */
    @CacheEvict
    public MiaoshaUser getByToken(HttpServletResponse response,String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }
        MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        if (null != user) {
            //延长有效期
            addCookie(response,token,user);
        }
        return user;
    }

    /**
     * 生成cookie
     * 将token添加到cookie中
     * @param response
     * @param user
     */
    private void addCookie(HttpServletResponse response,String token,MiaoshaUser user){
        //将用户信息写到redis当中(MiaoshaUserKey定义了miaosha业务专有的key)
        redisService.set(MiaoshaUserKey.token, token,user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN,token);
        //设置cookie的过期时间和在redis中保持一致
        cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
        cookie.setPath("/");
        //设置完成后，写到response中
        response.addCookie(cookie);
    }
}
